package com.pvdnc.tapkit.utils.encrypt;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESKeyUtils {
    private static byte[] generateSalt(int length){
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[length];
        random.nextBytes(salt);
        return salt;
    }

    public static final int AES_KEY_LENGTH=256;

    public static char[] getChars(byte[] data) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer buffer = ByteBuffer.allocate(data.length);
        buffer.put(data).flip();
        CharBuffer cb = cs.decode(buffer);
        return cb.array();
    }

    private static int getSaltLength(int keyLength){
        return keyLength/8;
    }

    public static SecretKey create(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        int saltLength = getSaltLength(AES_KEY_LENGTH);

        byte[] salt= generateSalt(saltLength);

        // 将密码明文、盐值等使用新的方法换算密钥
        int iterationCount = 1000;
        KeySpec keySpec = new PBEKeySpec(getChars(key), salt,
                iterationCount, AES_KEY_LENGTH);
        SecretKeyFactory keyFactory = SecretKeyFactory
                .getInstance("PBKDF2WithHmacSHA1");
        //生成AES-RawKey
        byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
        return new SecretKeySpec(keyBytes, "AES");
    }
}
